# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from time import sleep
from lxml import etree
import os
import requests

# 使用谷歌无头浏览器来加载动态js
def main():
    # 创建一个无头浏览器对象
    chrome_options = Options()
    # 设置它为无框模式
    chrome_options.add_argument('--headless')
    # 如果在windows上运行需要加代码
    chrome_options.add_argument('--disable-gpu')
    browser = webdriver.Firefox()
    # 设置一个10秒的隐式等待
    browser.implicitly_wait(10)
    browser.get(url)
    sleep(1)
    # 翻到页底
    browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')
    # 点击加载更多
    browser.find_element(By.CSS_SELECTOR, '.load_more_btn').click()
    sleep(1)
    # 再次翻页到底
    browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')
    # 拿到页面源代码
    source = browser.page_source
    browser.quit()
    with open('xinwen.html', 'w', encoding='utf-8') as f:
        f.write(source)
        parse_page(source)

# 对新闻列表页面进行解析
def parse_page(html):
    # 创建etree对象
    tree = etree.HTML(html)
    new_lst = tree.xpath('//div[@class="ndi_main"]/div')
    for one_new in new_lst:
        title = one_new.xpath('.//div[@class="news_title"]/h3/a/text()')[0]
        link = one_new.xpath('.//div[@class="news_title"]/h3/a/@href')[0]
        write_in(title, link)

# 将其写入到文件
def write_in(title, link):
    print('开始写入篇新闻{}'.format(title))
    response = requests.get(url=link, headers=headers)
    tree = etree.HTML(response.text)
    content_lst = tree.xpath('//div[@class="post_text"]//p')
    title = title.replace('?', '')
    with open('new/' + title + '.txt', 'a+', encoding='utf-8') as f:
        for one_content in content_lst:
            if one_content.text:
                    con = one_content.text.strip()
                    f.write(con + '\n')


if __name__ == '__main__':
    url = 'https://news.163.com/domestic/'
    headers = {"User-Agent": 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0'}
    if not os.path.exists('new'):
        os.mkdir('new')
    main()